package com.hlw.springboot.controller;

import com.alibaba.fastjson.JSONObject;
import com.hlw.springboot.entity.SysPermission;
import com.hlw.springboot.mapper.SysPermissionMapper;
import com.hlw.springboot.util.DataResult;
import com.hlw.springboot.util.TreeTableModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sysPer")
@Slf4j
public class SysPermissionController {

    @Resource
    private SysPermissionMapper sysPermissionMapper;


    /**
     * layui treeTable 权限列表数据获取
     * @return hlw
     */

    @RequestMapping(value="treeList")
    public Object findTypeTree()  {
        List<SysPermission> sysPermission =  sysPermissionMapper.selectAll();
        List<Object> list = new ArrayList<>();
        for (SysPermission m : sysPermission) {

            JSONObject treeObject = new JSONObject();
            if(m.getParentId()==1){
                treeObject.put("spread", true);//是否直接展开
            }
            treeObject.put("id", m.getId());
            treeObject.put("pid", m.getParentId());
            treeObject.put("name", m.getName());//tree的节点名称
            treeObject.put("url", m.getUrl());
            treeObject.put("permission", m.getPermission());
            treeObject.put("type", m.getType());
            list.add(treeObject);
        }
        return new TreeTableModel(list);
    }

    /**
     * 编辑权限
     * @param
     * @param
     * @return
     */
    @RequestMapping(value="savePermission",method= RequestMethod.POST)
    public DataResult innserPermission(@ModelAttribute("sysPermission")SysPermission sysPermission) {
        if(sysPermission.getId()==null){
            if(sysPermission.getParentId()==null){
                sysPermission.setParentId(0);
            }
            sysPermissionMapper.insert(sysPermission);
            return new DataResult(1,"操作成功");
        }else{
            sysPermissionMapper.updateByPrimaryKeySelective(sysPermission);
            return new DataResult(1,"操作成功");
        }
    }

    /**
     * 删除权限
     * 权限这一块进行删除时不直接删除数据库，只改变delflag的状态
     * @param
     * @param
     * @return
     */
    @DeleteMapping(value="delPermission")
    public DataResult deletePermission(int perId) {
      SysPermission sysPermission = sysPermissionMapper.selectByPrimaryKey(perId);
      sysPermission.setDelflag(1);
        sysPermissionMapper.updateByPrimaryKeySelective(sysPermission);
        return new DataResult(1,"操作成功");
    }

    /**
     * 根据查找权限
     * @param
     * @param
     * @return
     */
    @RequestMapping(value="findById",method= RequestMethod.POST)
    public DataResult findById(int perId) {
        SysPermission sysPermission = sysPermissionMapper.selectByPrimaryKey(perId);
        return new DataResult(1,"操作成功",sysPermission);
    }

    /**
     * 编辑菜单加载菜单树
     * @return
     */
    @RequestMapping(value="treeSelect")
    public Object treeSelect()  {
        List<SysPermission> sysPermission = sysPermissionMapper.selectAll();
        List<Object> list = new ArrayList<>();
        for (SysPermission permission : sysPermission) {
            if(permission.getParentId()==0){//判断是否是一级菜单
                JSONObject treeObject = new JSONObject();
                treeObject.put("id", permission.getId());
                treeObject.put("name", permission.getName());//tree的节点名称
                treeObject.put("open", true);
                treeObject.put("children", getChildren(permission.getId(),sysPermission));//孩子节点，递归遍历
                list.add(treeObject);
            }
        }
        return list;
    }


    public List<Object> getChildren(Integer parentId,List<SysPermission> menus){
        List<Object> list = new ArrayList<>();
        for (SysPermission m : menus) {
            if(m.getParentId().equals(parentId)){
                JSONObject obj = new JSONObject();
                obj.put("id", m.getId());
                obj.put("name", m.getName());
                obj.put("open", false);
                obj.put("children", getChildren(m.getId(),menus));
                list.add(obj);
            }
        }
        return list;
    }

    /**
     * layui列表进行编辑
     * @param
     * @param
     * @return
     */
    @PutMapping(value="updateById")
    public DataResult updateById(int perId,String content,String fieldName) {
        Map<String, Object> map = new HashMap<>();
        map.put("id",perId);
        map.put("content",content);
        map.put("fieldName",fieldName);
        int count = sysPermissionMapper.updateById(map);
        if(count>0){
            return new DataResult(1,"操作成功");
        }else {
            return new DataResult(404,"操作失败");
        }
    }

    /**
     * 角色设置权限用的tree
     * @return
     */

    @RequestMapping(value="layuiTree")
    @ResponseBody
    public DataResult layuitree()  {
        List<SysPermission> permissionList =  sysPermissionMapper.selectAll();
        List<Object> list = new ArrayList<>();
        for (SysPermission m : permissionList) {
            if(m.getParentId()==0){//判断是否是一级菜单
                JSONObject treeObject = new JSONObject();
                treeObject.put("id", m.getId());
                treeObject.put("title", m.getName());//tree的节点名称
                treeObject.put("spread", true);
                treeObject.put("field", m.getName());
                treeObject.put("children", getChildrenTree(m.getId(),permissionList));//孩子节点，递归遍历
                list.add(treeObject);
            }
        }
        System.out.println(list);
        return  new DataResult(0,"获取成功",list);

    }

    public List<Object> getChildrenTree(int parentId,List<SysPermission> menus){
        List<Object> list = new ArrayList<>();
        /*    List<Menu> plist = mapper.findPermissionByRoleId(rid);//获取用户权限
         */
        for (SysPermission m : menus) {
            if(m.getParentId().equals(parentId)){
                JSONObject obj = new JSONObject();
                obj.put("id", m.getId());
                obj.put("title", m.getName());//tree的节点名称
                obj.put("field", m.getName());
                obj.put("spread",true);
                obj.put("children", getChildrenTree(m.getId(),menus));
                list.add(obj);
            }
        }
        return list;
    }

    /**
     * 根据角色Id 查询角色权限
     *
     * @param roleId
     * @return
     */
    @RequestMapping("/findPerByRoleId")
    public DataResult setPer(Integer roleId) {
        List<SysPermission> plist = sysPermissionMapper.findPermissionByRoleId(roleId);// 获取角色权限
        List<SysPermission> menus = plist.stream().filter(p ->p.getDelflag()==0).collect(Collectors.toList());// p.getType()==0&& 以后再用，分前后台的菜单
        if (!menus.equals(null)) {
            List<Integer> perminsStrlist = new ArrayList<Integer>();// 角色的权限集合
            for (SysPermission uPermission : menus) {
                if (uPermission.getParentId() != 0) {
                    perminsStrlist.add(uPermission.getId());
                    System.out.println(perminsStrlist);
                }
            }
            return new DataResult(1,"获取成功",perminsStrlist);
        }else{
            return   new DataResult(1,"无消息");
        }
    }

    /**
     * 角色设置权限。权限可为null
     */
    @RequestMapping("/updatePer")
    @ResponseBody
    public DataResult updatePer(int[] arr, int rid) {
        if(arr!=null){
            List<SysPermission> menus = sysPermissionMapper.findPermissionByRoleId(rid);
            if (menus.size()>0 ) {
                sysPermissionMapper.deletePerByrid(rid);
                    for (int item : arr) {
                        sysPermissionMapper.inserPerByRid(rid, item);
                        }
                    return new DataResult(1,"操作成功");
                } else {
                    for (int item : arr) {
                        sysPermissionMapper.inserPerByRid(rid, item);
                    }
                    return new DataResult(1,"操作成功");
                      }
        }else{
                sysPermissionMapper.deletePerByrid(rid);
                return new DataResult(1,"操作成功");
        }
    }



}
